<?php
	include_once('dbcon.php');
	include_once('constants.php');
	include_once('update_user_points_db.php');
	include_once('general_functions_db.php');

	$addedToLikes = false;
	$addedToDislikes = false;

	function checkForRemove($content) {
		$total_qualifications = ($content['likes'] + $content['dislikes']);

		if ($total_qualifications == 0) {
			return;
		}

		$fraction_likes = $content['likes'] / $total_qualifications;

		if ($fraction_likes <= LIKES_FRACTION_REMOVE_CONTENT_NEEDED && $total_qualifications >= QUALIFICATIONS_REMOVE_CONTENT_NEEDED) {
			removeContent($content['content_id']);
		} 
	}

	function insertUpdateCalificationEntry($user_id, $content_id, $calification_by_user) {
		global $mysqli;
		global $addedToLikes;
		global $addedToDislikes;

		$calification = $mysqli->query("SELECT calification FROM contents_califications WHERE user_id=".$user_id." && content_id=".$content_id);
		logIfError($mysqli, $user_id, "rate_content_db.php", "insertUpdateCalificationEntry", "1");

		$mysqli->autocommit(false);

		if ($calification->num_rows == 0) {

			$mysqli->query("INSERT INTO contents_califications (user_id, content_id, calification, date) VALUES('".$user_id."','".$content_id."','".$calification_by_user."','".date('Y-m-d H:i:s')."')");

			if ($calification_by_user == "1") {
				$mysqli->query("UPDATE contents SET likes=likes+1 WHERE content_id=".$content_id);
				$addedToLikes = true;
			} else {
				$mysqli->query("UPDATE contents SET dislikes=dislikes+1 WHERE content_id=".$content_id);
				$addedToDislikes = true;
			}

		} else {
			$result = $calification->fetch_assoc();

			if ($result['calification'] == $calification_by_user) {
				return;
			} else if ($result['calification'] == "-1" && $calification_by_user == "1") {
				$mysqli->query("UPDATE contents SET likes=likes+1, dislikes=dislikes-1 WHERE content_id=".$content_id);
			} else if ($result['calification'] == "1" && $calification_by_user == "-1") {
				$mysqli->query("UPDATE contents SET likes=likes-1, dislikes=dislikes+1 WHERE content_id=".$content_id);
			}

			$mysqli->query("UPDATE contents_califications SET calification=".$calification_by_user.", date=\"".date('Y-m-d H:i:s')."\" WHERE user_id=".$user_id." && content_id=".$content_id);
		}

		$mysqli->commit();
		logIfError($mysqli, $user_id, "rate_content_db.php", "insertUpdateCalificationEntry", "2");

		$mysqli->autocommit(true);
	}

	function updateCategoryScore($category_id, $previousPoints, $currentPoints, $previousLikes, $previousDislikes, $currentLikes, $currentDislikes) {
		global $mysqli;

		if ($previousPoints < MIN_POINTS_TO_BESTS && $currentPoints < MIN_POINTS_TO_BESTS )
			return;

		$category_query = $mysqli->query("SELECT category_id, likes, dislikes, creation_date FROM categories WHERE category_id='".$category_id."'");
		logIfError($mysqli, $_REQUEST['user_id'], "updateCategoryScore.php", "rateContent", "1");
		$category = $category_query->fetch_assoc();

		$likes = 0;
		$dislikes = 0;

		if ($previousPoints >= MIN_POINTS_TO_BESTS && $currentPoints >= MIN_POINTS_TO_BESTS ) {
			$likes = $category['likes'] -  $previousLikes + $currentLikes;
			$dislikes = $category['dislikes'] - $previousDislikes + $currentDislikes;
		}

		if ($previousPoints >= MIN_POINTS_TO_BESTS && $currentPoints < MIN_POINTS_TO_BESTS ) {
			$likes = $category['likes'] -  $previousLikes;
			$dislikes = $category['dislikes'] - $previousDislikes;
		}

		if ($previousPoints < MIN_POINTS_TO_BESTS && $currentPoints >= MIN_POINTS_TO_BESTS ) {
			$likes = $category['likes'] +  $currentLikes;
			$dislikes = $category['dislikes'] + $currentDislikes;
		}

		$mysqli->query("UPDATE categories SET score='".getCategoryScore($likes, $dislikes, $category['creation_date'])."', likes='".$likes."', dislikes='".$dislikes."' WHERE category_id='".$category_id."'");
		logIfError($mysqli, $_REQUEST['user_id'], "updateCategoryScore.php", "rateContent", "2");
	}

	function rateContent($user_id, $content_id, $calification) {
		global $mysqli;
		global $addedToLikes;
		global $addedToDislikes;

		if (isUserValid($user_id) == false) {
			logMsg($user_id, "RATE CONTENT INVALID, INVALID USER. ContentId=".$content_id.". Calification=".$calification);
			return;
		}

		insertUpdateCalificationEntry($user_id, $content_id, $calification);

		$content_query = $mysqli->query("SELECT content_id, category_id, likes, dislikes, user_id FROM contents WHERE content_id='".$content_id."'");
		logIfError($mysqli, $user_id, "rate_content_db", "rateContent", "1");
		$content = $content_query->fetch_assoc();

		$currentPoints = getContentPoints($content['likes'], $content['dislikes']);

		$mysqli->query("UPDATE contents SET points='".$currentPoints."' WHERE content_id='".$content_id."'");
		logIfError($mysqli, $user_id, "rate_content_db.php", "rateContent", "2");
		
		$previousLikes = ($addedToLikes == true) ? $content['likes'] - 1: $content['likes'];
		$previousDislikes = ($addedToDislikes == true) ? $content['dislikes'] - 1: $content['dislikes'];
		$previousPoints = getContentPoints($previousLikes, $previousDislikes);

		updateCategoryScore($content['category_id'], $previousPoints, $currentPoints, $previousLikes, $previousDislikes, $content['likes'], $content['dislikes']);

		checkForRemove($content);
		
		updateUserPoints($content['user_id']);
	}

	if (isset($_REQUEST['user_id']) && isset($_REQUEST['content_id']) && isset($_REQUEST['calification'])) {
		logMsg($_REQUEST['user_id'], "Rate content. ContentId=".$_REQUEST['content_id'].". Calification=".$_REQUEST['calification']);
		rateContent($_REQUEST['user_id'], $_REQUEST['content_id'], $_REQUEST['calification']);
	}
?>

